		var browser={
            versions:function() {
                var u=navigator.userAgent, app = navigator.appVersion;
                return {//移动终端浏览器版本信息
                    trident: u.indexOf('Trident') > -1, //IE内核
                    presto: u.indexOf('Presto') > -1, //opera内核
                    webKit: u.indexOf('AppleWebKit') > -1, //苹果、谷歌内核
                    gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') == -1, //火狐内核
                    mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/), //是否为移动终端
                    ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), //ios终端
                    android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, //android终端或者uc浏览器
                    iPhone: u.indexOf('iPhone') > -1 || u.indexOf('Mac') > -1, //是否为iPhone或者QQHD浏览器
                    iPad: u.indexOf('iPad') > -1, //是否iPad
                    webApp: u.indexOf('Safari') == -1 //是否web应该程序，没有头部与底部
                };
            }(),
            language:(navigator.browserLanguage || navigator.language).toLowerCase()
        }
		var iphone = false;
		var htmlVersion = "WEB";
		if(navigator.userAgent.indexOf('MicroMessenger') > -1){
            if(browser.versions.ios || browser.versions.iPhone || browser.versions.iPad){
               iphone = true;
               htmlVersion = "IOS";
            }else if(browser.versions.android){
               htmlVersion = "AD";
            }
        }
		var nowStatus = "-1";
		var nowPay = false;
    	// 区域滚动调用方法
        var myScroll = new IScroll('#wrapper',{scrollX: true,scrollY: true,freeScroll: true});       
        
        //点击播放视频
        function playLive(){
        	if(nowPay){
        		if(nowStatus == "0" || nowStatus == "1" ){
            		alert("直播尚未开始 请稍后");            		
            	}else if(nowStatus == "2"){
                	$("#videoBack").hide();
        			$("#video").hide();
        			$('#videoLive').show();
    				$('#videoLive').attr("autoplay","autoplay");
        			if(iphone){
                    	var video = $('#videoLive');
                    	video.play();
        			}else{
        				$('#videoLive').unbind().click(function(){
        					var video = document.getElementById('videoLive');
                        	video.play();
        				});
        				$('#videoLive').click();
        			}
            	}else if(nowStatus == "3"){
            		alert("直播已结束 稍后可观看回放");
            	}else if(nowStatus == "4"){
        			$("#video").hide();
        			$('#videoLive').hide();	
                	$("#videoBack").show();
            	}else if(nowStatus == "6"){
            		alert("直播已结束 感谢您的关注");
            	}else{
            		alert("直播已被删除");
            	}
        	}
        }
		//记录播放人数
        function playVideoCount(){
        	$.ajax({
				url : "../proxy/galaxy/v1/livevideo/playCount",
				type : 'post',
				data : {
					    "liveId":liveId,
						"userId":userId
					   },
				dataType : "json",
				success : function(data) {
					$("#liveNum").html(isValid(data.playCount,"0") +"人看过");
				}
			});
        } 
		
        //下单
       function createOrder(userIp,callback){
        	$.ajax({
				url : "../proxy/galaxy/v1/livevideo/order/live/"+liveId,
				type : 'post',
                dataType : "json",
                data:{"userIp":userIp},
				beforeSend:function(){
			        //请求前的处理
			    	$(".loading").show();
			        $("#payBtn").attr("style","background:#444444");
			        $("#payBtn").attr("disabled","disabled");
			    },
                contentType: 'application/json;charset=utf-8',
				success : function(data) {
					callback(data);
				},
				complete:function(){
		    		$(".loading").hide();
		    		$("#payBtn").attr("style","");
			        $("#payBtn").attr("disabled",false);
			    },
				error:function(e){
					alert("系统忙，请稍后再试");
			        $("#payBtn").show();
				}
			});
        } 
        
       //Tab事件注册 主要是直播和点播两者排版不同
       function regTab(ispay,status){
    	   if(status == "2" && ispay){//直播中且付费排版
    		   $('#noCommentDiv').hide();
    		   $(".tab_ul li:eq(0) p:eq(0)").html("聊天室");
    		   $(".tab_ul li:eq(1) p:eq(0)").html("详情");
    		   $(".tab_ul li:eq(1)").click(function(){
	   				$(this).addClass("new").siblings().removeClass("new");
	   				$(".introduce").show();
	   				$(".talk").hide();
	   			});				
	   			$(".tab_ul li:eq(0)").click(function(){
	   				$(this).addClass("new").siblings().removeClass("new");
	   				$(".introduce").hide();
	   				$(".talk").show();	
	   				myScroll.refresh();
	   				myScroll.scrollTo(0,0,0,IScroll.utils.ease.quadratic);						
	   			});
    	   }else{
    		   $(".tab_ul li:eq(0) p:eq(0)").html("详情");
    		   $(".tab_ul li:eq(1) p:eq(0)").html("评论");
    		   $(".tab_ul li:eq(1)").click(function(){
	   				$(this).addClass("new").siblings().removeClass("new");
	   				$(".introduce").hide();
	   				$(".talk").show();
	   				myScroll.refresh();
	   				myScroll.scrollTo(0,0,0,IScroll.utils.ease.quadratic);	
	   			});				
	   			$(".tab_ul li:eq(0)").click(function(){
	   				$(this).addClass("new").siblings().removeClass("new");
	   				$(".introduce").show();
	   				$(".talk").hide();						
	   			});
    	   }   
       }
        //初始化播放页
        function initLiveDetail(callback){
			$.ajax({
				url:"../proxy/galaxy/v1/livevideo/"+liveId+"/detail",
				type:'get',
				dataType:'json',
				data:{
					  "liveId":liveId
				      },
				async: false,
				success : function(data) {
					if(data == null){
						alert("该视频资源不存在！");
						return;
					}
					var price = isValid(data.playPrice,"");
					var ispay = isValid(data.paid,0);
					var status = isValid(data.liveStatus,"");
					var hasPwd = isValid(data.hasPassword,"");
					
					//机构假数据
					if(liveId == 'yQjpRZWTTmqMJs2t11ymcA'){
						fakeNum = 1210;
					}
					//五四青年节活动
					if(liveId == "v2No4NriThaenckTMhq3dQ" || liveId == "8atQ0ZcTTGSGHi05BWN7JQ"){
						var stime = data.showTime;
						fakeNum = getFakeNum(stime);
						actNum = parseInt(isValid(data.playCount,'0'));
						data.playCount = actNum + fakeNum;
						//定时任务刷基数
						var interval = setInterval(function(){
							var nn2 = new Date().getTime()-stime;
							var mm2 = Math.round((nn2 / (1000 * 60)));
							if(mm2 > 0 && mm2 <= 60){
								fakeNum = getFakeNum(stime);
								$("#liveNum").html((fakeNum+actNum)+"人看过");
							}
							if(mm2 > 60){
								clearInterval(interval);
							}
						//do whatever here..
						}, 10000);
					}
					
					
					/*****设置直播介绍开始*******/
					//直播介绍设置
					$("#liveTitle").html(isValid(data.liveTitle,""));
                    $("#video").css("background","url("+data.livePoster+")");
                    $("#video").css("background-size","100% 100%");
                    $("#videoBack").css("background","url("+data.livePoster+")");
                    $("#videoBack").css("background-size","100% 100%");
					if(iphone){
						//$("#videoLive").attr("poster",data.livePoster);
					}
					$("#liveType").html(isValid(data.contentClassify,""));
					$("#livePrice").html("￥"+isValid(data.playPrice,"0.00"));
					$("#liveNum").html(isValid(data.playCount,"0")+"人看过");
					$("#liveDesc").html(isValid(data.liveDesc,""));
					$("#zbAvatar").attr("src",isValid(data.avatar,"images/avatar.png"));
					$("#zbName").html(isValid(data.anchorName,""));
					$("#zbLiveSize").html(isValid(data.liveSize+"次直播",""));
					$("#zbOrg").html(isValid(data.cooperateOrgName,""));
					$("#zbDesc").html(isValid(data.introduce,""));
					/*****设置直播介绍结束*******/
					
					/*==============播放页tab======================*/
					regTab(ispay,status);
					
					//当前支付状态
					nowPay = ispay;
					if(ispay){					
						$('#msgDiv').show();
						var playListStr = "";
						if(status == "0" || status == "1"){//未开始
							$("#liveNum").html(isValid(data.playCount,"0")+"人报名");
						}else if(status == "2"){//直播中			
							var playUrl = isValid(data.playUrl,"");
							if(playUrl.length > 0){
								//playListStr = '<source src="'+data.playUrl+'"></source>';
								//var video = $("#videoLive");
								//$(playListStr).appendTo(video);
								$("#videoLive").attr("src",data.playUrl);
							}	
						}else if(status == "3"){//转码中 不可播放回看
						}else if(status == "4"){//已结束 可看回看
							playListStr = "[";
						    if(undefined != data.playbackUrl){
							    var playbackUrl = isValid(data.playbackUrl,"");
							    var urls = playbackUrl.split(",");
								for(var i=0;i<urls.length;i++){
									var f = urls[i];
									if("" != f && undefined != f){
										playListStr+="{image:'"+data.livePoster+"',sources:[{file:'"+f+"'}]}";
										if(i < urls.length - 1){
											playListStr +=",";
										}
									}		
								}
						    }							
							playListStr += "]";
							
							var plays = eval(playListStr);
							if(plays.length > 0){
								var videoWidth = document.body.scrollWidth;
						    	player = cyberplayer("videoBack").setup({
						            width: videoWidth,
						            height: videoWidth/1.8,
						            primary: "videojs",
						            //stretching: "uniform",
						            stretching: "fill",
						            autostart: true,
						            repeat: false,
						            volume: 100,
						            controls: true,
						            hls: {
						                reconnecttime: 5 // hls直播的重连次数
						            },
						            controlbar: {
						                barLogo: false, // 进度条上的logo显示与否,默认true
						                //barLogoUrl: "https://www.tudou.com/", // 进度条上的logo的跳转地址可配置
						                canDrag: true // 进度条是否允许拖动,默认true
						            },
						            playlist: plays,
						            ak:'70e7493fff444158adc750be22be3146'
						        });							
							}else{
								//如果状态为6但是没回看地址
								status = "6";	
							}	
						}		
					}else{
						if(status == "0" || status == "1"){
	                        $("#liveNum").html(isValid(data.playCount,"0")+"人报名");
						}
						$('#msgDiv').hide();
						var p = isValid(price,0);
						if(p!=0){
							$("#videoLive").hide();
							$("#videoBack").hide();
							$("#liveBtn").hide();
							$("#video").show();
							$("#payBtn").attr("value","￥"+price+" 报名观看");
						}else{
							//费用为0则走免费流程
							/*if(!ispay){
								createOrder();	
							}
							ispay = true;//当做已付费
							$('#msgDiv').show();//出现聊天框*/
						}						
					}
					//设置播放状态以及播放层展示效果
					setLiveStatus(status);
					callback(data);			
				},error:function(e){
					console.log(e);
		        }
			});
        }        
        
    //设置直播状态
    function setLiveStatus(status){
		$("#video").find("p:eq(0)").hide();
		$("#video").find("p:eq(1)").hide();
    	nowStatus = status;
    	var str = "";
    	if(status == "0" || status == "1"){
			str = "直播尚未开始";
			$("#videoLive").hide();
			$("#videoBack").hide();
			$("#video").show();
			$("#liveBtn").hide();
			if(nowPay){
                $("#video").find("p:eq(1)").find("input:eq(0)").val("直播未开始");
                $("#video").find("p:eq(1)").show();
			}
    	}else if(status == "2"){
    		str = "直播中";
    		$('#liveShow').show();
    		if(!iphone){
				$("#videoLive").hide();
				$("#videoBack").hide();
				$("#video").show();
				$("#liveBtn").show();
    		}else{
				$("#videoLive").show();
				$("#videoBack").hide();
				$("#video").hide();
				$("#liveBtn").hide();
    		}			
    	}else if(status == "3" || status == "6"){
    		str = "直播已结束";
			$("#videoLive").hide();
			$("#videoBack").hide();
			$("#video").show();
			$("#liveBtn").hide();
			$("#video").find("p:eq(1)").find("input:eq(0)").val("直播已结束");
			$("#video").find("p:eq(1)").show();
			$("#liveShow").hide();
    	}else if(status == "4"){
    		str = "直播已结束";
			$("#videoLive").hide();
			$("#video").hide();
			$("#liveBtn").hide();
			$("#videoBack").show();
    	}else if(status == "5"){
    		str = "直播已删除";
			$("#videoLive").hide();
			$("#videoBack").hide();
			$("#video").show();
			$("#liveBtn").hide();
			$("#video").find("p:eq(1)").find("input:eq(0)").val("直播已删除");
			$("#video").find("p:eq(1)").show();
    	}

    	if(!nowPay){
			$("#videoLive").hide();
			$("#videoBack").hide();
			$("#video").show();
			$("#video").find("p:eq(0)").show();
			$("#liveBtn").hide();
    	}
		$('#liveStatus').html(str);
    }
    
	//聊天TAB功能
	function showMessage(jsonS,opType){
		var pushObj = eval('(' + jsonS + ')');
		var pushType = pushObj.pushType;
		var pushContent = pushObj.pushContent;
		
		var msgType = pushContent.msgType;
		var userId =pushContent.userId;
		var msgUserName = pushContent.userName;
		var msgUserImg =pushContent.userImg;
		var msgContent = eval('(' + pushContent.content + ')');
		
		var msgId = pushContent.msgId;
		var msgClass = "message";
		var msgHtml = null;		
		if(pushType == 'sys'){
			if(msgType == "live_into_room"){
				msgClass = "join";
				msgHtml = '<div class="message">'+
							 '<dl>'+
								'<dt>'+msgUserName+' 进入直播间。</dt>'+
							'</dl>'+
						'</div>';
			}else if(msgType == "live_end_wx"){
				alert("直播已结束");
				setLiveStatus("3");
			}else if(msgType == "live_play_recrod_count"){
				if(liveId == "v2No4NriThaenckTMhq3dQ"){
					var liveNum = fakeNum+parseInt(isValid(msgContent.playCount,'0'));
					actNum = parseInt(isValid(msgContent.playCount,'0'));
					$("#liveNum").html(liveNum + "人看过");
				}else{
					$("#liveNum").html(isValid(msgContent.playCount,liveNum) +"人看过");
				}
			}else if(msgType == "live_start"){
				var playUrl = msgContent.playUrl;
				if(undefined != playUrl && playUrl.length > 0){
					$('#liveStatus').html("直播中");
					$("#videoLive").attr("src",playUrl);
					setLiveStatus("2");
					playLive();
				}
			}else if(msgType == "redPkg"){
				alert("红包来了");
			}else if(msgType == "live_reward"){
				msgClass = "join";
				msgHtml = '<div class="message">'+
							 '<dl>'+
								'<dt>'+msgUserName+' 打赏了 '+msgContent.rewardMoney+' 元。</dt>'+
							'</dl>'+
						'</div>';
			}else if(msgType == "live_reward_goods"){
				var giftHtml = "";
				var gid = msgContent.goodsId;
				if(gid == "w_balloon"){
					giftHtml = '<i><img src="images/liwu1.png"/></i>';
					$(".qqdh").appendTo("body");
					$(".qqdh").show();
					qqdh();
				}else if(gid == "w_flower"){
					giftHtml = '<i><img src="images/liwu2.png"/></i>';
					$(".xhdh").appendTo("body");
					$(".xhdh").show();
					xhdh();
				}else if(gid == "w_kiss"){
					giftHtml = '<i><img src="images/liwu3.png"/></i>';
					$(".jwdh").appendTo("body");
					$(".jwdh").show();
					jwdh();
				}else if(gid == "w_crane"){
					giftHtml = '<i><img src="images/liwu4.png"/></i>';
					$(".szdh").appendTo("body")
					$(".szdh").show();
					szdh();
				}
				msgClass = "join";
				msgHtml = '<div class="message">'+
							 '<dl>'+
								'<dt> 收到 '+msgUserName+' 赠送的'+giftHtml+'</dt>'+
							'</dl>'+
						'</div>';
			}
		}else if(pushType == 'msg'){
			if(msgType == "text"){
				var text = 
				msgHtml = '<div class="message">'+
							 '<dl>'+
								'<dt>'+msgUserName+'：</dt>'+
								'<dd>'+msgContent.text+'</dd>'+
							'</dl>'+
						'</div>';
			}
		}
		if(opType=="down" && msgHtml != null){
			$("#scroller").append(msgHtml);
			myScroll.refresh();
			myScroll.scrollTo(0,myScroll.maxScrollY,500,IScroll.utils.ease.quadratic);
		}		
	}
	
	//MQTT连接
	function MQTTConnect(callback){
		if (!connectFlag )
		{
		    client.connect({
			  onSuccess:onConnect,
		      onFailure:onConnectFail,
			  keepAliveInterval:30,
			  useSSL:MQTTHttps
		    });
		}
	}
	
	//连接成功回调
	function onConnect() {
		connectFlag = true;
		client.subscribe(liveId);
		//进入房间提示
		var jsonS = '{"pushType": "sys", "pushContent":{"msgType":"live_into_room","userName": "'+userName+'"}}';
		var message = new Paho.MQTT.Message(jsonS);
		message.destinationName = liveId;
		client.send(message);
	}
	
	//连接失败回调
	function onConnectFail() {
	}
	
	//连接断开通知
	function onConnectionLost(responseObject) {
		console.error(responseObject);
        if (8 === responseObject.errorCode) {
            connectFlag = true;
        }else if (responseObject.errorCode !== 0) {
		 	connectFlag = false;
		}
	}
	
	//消息接收通知
	function onMessageArrived(message) {
		var jsonS = message.payloadString;
		showMessage(jsonS,"down");
	}
	
	//发送消息 接口调用
	function sendMessage(msgType,msg,duration,callback){		
		var jsonS = '{"text":"'+msg+'"}';

		var jsonData = {
            "sendUserId":userId,
            "pushType":"msg",
            "msgType":msgType,
            "content":jsonS,
            "liveId":liveId,
            "userName":userName,
            "userImg":userImg
        };
		var data = JSON.stringify(jsonData);
		//保存消息
		$.ajax({    
			url:"../proxy/galaxy/v1/wx/sendMsg",
			type:'post',
			dataType:'json',
			data:data,
            contentType: 'application/json;charset=utf-8',
			async:true,//需要获取后台返回的msgId
			success:function(data){
		   	},
		   	complete:function(){
		   		callback();
		   	},
			error:function(){
				alert("系统忙，请稍后再试");
			}
		});
	}
		
	//发送文本消息
	function sendTxt(id){
		var msgTxt = $("#"+id).val();
		if(null == msgTxt || msgTxt == ""){
			alert("发送内容不能为空！");
			$("#"+id).focus();
			return;
		}
		sendMessage("text",msgTxt,"",function(){
            //if(msgType=='text'){
                $("#"+id).val("");
            	if(id=="msgTxt"){//文本框
        			$('.send').hide();
        			$('.reward').show();
            	}else{//文本域隐藏
            		$('.input_pop').hide();
            	}
            //}
		});
	}
	
	
	
	
	function buyCourse(){
		var goodsId = $("#courseGoodsId").val();
		createOrder(goodsId,"1","0",function(){
			$(".bcBtn1").removeAttr("onclick");
		},function(){
			$(".bcBtn1").attr("onclick","buyCourse()");
		},function(data){
			//console.log('create order success');
			if(data.status == '0'){
				var orderId = data.orderId;
				//console.log('orderId='+orderId);
				toPay(orderId,function(){
					window.location.reload();
				});
			}else{
				alert(data.msg);
			}
		},function(){
			//console.log('create order error');
		});
	}
	
	//*************************************评论区*******************************************
	var commentIndex = 1;//页码
	var existComment = true;//是否存在评论
	function initCommentList(){
		//加载第一页评论
		loadCommentList(commentIndex);
		//注册滚动翻页事件
		regCommentLoad();
	}
	
	
	//显示评论
	function showComment(data,isTop){
		var headImg = data.avatar;
		var userName = data.userName;
		var commentTime = new Date(data.createTime).Format('yyyy-MM-dd hh:mm');
		var commentContent = data.content;
		var replayHtml = "";

		if(!isTop){
			var replaylist = data.replays;
			for(var i=0; i<replaylist.length; i++){
				var replay = replaylist[i];
				replayHtml += '<p class="zbhf"><em>主播回复：</em>'+replay.content+'</p>';
			}
		}
		var commentHtml = '<div class="message2">'+
			'<dl>'+
				'<dt><img src="'+headImg+'"></dt>'+
				'<dd>'+
	            	'<span><em>'+userName+'</em>'+commentTime+'</span>'+
	            	'<p>'+commentContent+'</p>'+
	            	replayHtml +
	            '</dd>'+
			'</dl>'+
		'</div>';
		if(data != null){
			if(!$("#noCommentDiv").is(":hidden")){
				$('#noCommentDiv').hide();
			}
			if(isTop){
				$("#scroller").prepend(commentHtml);	
			}else{				
				$("#scroller").append(commentHtml);
			}
			myScroll.refresh();
			//myScroll.scrollTo(0,myScroll.maxScrollY,500,IScroll.utils.ease.quadratic);
		}		
	}
	
	//加载评论信息
	function loadCommentList(pageNum){
		if(pageNum == 1){
			$('#noCommentDiv').show();
		}
		$.ajax({
			url:"../proxy/galaxy/v1/comments/liveid/"+liveId,
			type:'get',
			dataType:'json',
			data:{"page":pageNum,"rows":10},
			async: false,
			success : function(data) {
				var contents = data.contents;
				if(contents.length < 1){
					existComment = false;
					commentIndex--;
				}else{
					existComment = true;
					for(var i=0;i<contents.length;i++){
				   		showComment(contents[i],false);	
					}	
				}	
			},error:function(e){
				console.log(e);
	        }
		});
		
    }        
	
	//注册滚动翻页功能
	function regCommentLoad(){
		myScroll.on("scrollEnd",function(e){
            if(myScroll.maxScrollY == myScroll.y){
            	if(existComment){
    				commentIndex++;	
                	loadCommentList(commentIndex);
            	}
            }   
    	});
	}
		
	//发表评论
	function sendComment(id){
		var msgTxt = $("#"+id).val();
		if(null == msgTxt || msgTxt == ""){
			alert("发送内容不能为空！");
			$("#"+id).focus();
			return;
		}
		var jsonData = {
            "type":'text',"content":msgTxt
        };
		var data = JSON.stringify(jsonData);
		//保存消息
		$.ajax({    
			url:"../proxy/galaxy/v1/comments/liveid/"+liveId,
			type:'post',
			dataType:'json',
			data:msgTxt,
            contentType: 'application/json;charset=utf-8',
			async:true,//需要获取后台返回的msgId
			success:function(data){
				showComment(data,true);					
		   	},
		   	complete:function(){
		   		$("#"+id).val("");
            	if(id=="msgTxt"){//文本框
        			$('.send').hide();
        			$('.reward').show();
            	}else{//文本域隐藏
            		$('.input_pop').hide();
            	}
		   	},
			error:function(){
				alert("系统忙，请稍后再试");
			}
		});
	}